<template>
  <div class="user-management">
    <!-- 搜索表单 -->
    <a-card>
      <a-form style="width: 100%;" layout="inline" :label-col="{ style: { width: '80px', textAlign: 'left' } }"
        :model="searchForm" @finish="handleSearch">
        <div class="user-form">
          <a-row :gutter="[16, 16]">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="用户名">
                <a-input v-model:value="searchForm.username" placeholder="请输入用户账号" allowClear />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="昵称">
                <a-input v-model:value="searchForm.nickname" placeholder="请输入昵称" allowClear />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="电话号码">
                <a-input v-model:value="searchForm.phone" placeholder="请输入电话号码" allowClear />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="是否禁用">
                <a-select v-model:value="searchForm.isBan" allowClear>
                  <a-select-option :value="0">启用</a-select-option>
                  <a-select-option :value="1">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="创建时间">
                <a-range-picker v-model:value="searchForm.create_time" style="width: 100%" allowClear />
              </a-form-item>
            </a-col>
          </a-row>
          <div class="form-btn">
            <a-form-item>
              <a-button type="link" @click="resetSearch">重置</a-button>
              <a-button type="primary" html-type="submit">搜索</a-button>
            </a-form-item>
          </div>
        </div>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card style="margin-top: 16px" class="table-body">
      <div class="action-buttons">
        <a-space>
          <a-button type="primary" @click="showAddModal">
            <template #icon><plus-outlined /></template>
            添加用户
          </a-button>
        </a-space>

        <a-dropdown>
          <template #overlay>
            <a-menu @click="handleBatchAction">
              <a-menu-item key="delete">
                <delete-outlined /> 删除
              </a-menu-item>
              <a-menu-item key="un-ice">
                <unlock-outlined /> 解禁
              </a-menu-item>
              <a-menu-item key="ice">
                <lock-outlined /> 禁用
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>
            批量操作 <down-outlined />
          </a-button>
        </a-dropdown>
      </div>
      <div class="table-contaier" ref="tableContainerRef">
        <a-table :scroll="{ y: tableHeight + 'px' }" :loading="loading" :columns="columns" :data-source="userList"
          :pagination="pagination" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          row-key="user_id" @change="handleTableChange">
          <template #bodyCell="{ column, record,index }">
            <template v-if="column.key === 'index'">
              {{index+1}}
            </template>
            <template v-if="column.key === 'avatar'">
              <a-avatar :src="record.avatar" :style="{ backgroundColor: '#f56a00' }" />
            </template>
            <template v-if="column.key === 'isAdmin'">
              {{ record.isAdmin ? '是' : '否' }}
            </template>
            <template v-else-if="column.key === 'isBan' && !record.isAdmin">
              <a-switch :checked="record.isBan" checked-children="开启" un-checked-children="关闭"
                @change="(checked) => handleSwitchChange(checked, record)" />
            </template>
            <template v-else-if="column.key === 'create_time'">
              {{ formatTime(record.create_time) }}
            </template>
            <template v-else-if="column.key === 'update_time'">
              {{ formatTime(record.update_time) }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a @click="showUpdatePasswordModal(record)">修改密码</a>
                <a-popconfirm title="你确定删除此用户吗?" ok-text="确定" cancel-text="取消" @confirm="confirmDelete(record)">
                  <a>删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>

    <!-- 添加用户模态框 -->
    <a-modal centered v-model:visible="addModalVisible" title="添加用户">
      <a-form ref="addFormRef" :model="addForm" :rules="addFormRules" layout="vertical">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="addForm.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="addForm.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="addForm.nickname" placeholder="请输入昵称" />
        </a-form-item>
        <a-form-item label="电话号码" name="phone">
          <a-input v-model:value="addForm.phone" placeholder="请输入电话号码" />
        </a-form-item>
        <a-form-item label="性别" name="sex">
          <a-select v-model:value="addForm.sex" placeholder="请选择性别">
            <a-select-option :value="1">男</a-select-option>
            <a-select-option :value="0">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否禁用" name="isBan">
          <a-select v-model:value="addForm.isBan" placeholder="请选择状态">
            <a-select-option :value="0">启用</a-select-option>
            <a-select-option :value="1">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="resetAddForm">取 消</a-button>
        <a-button key="submit" type="primary" :loading="addFormLoading" @click="handleAddUser">确 定</a-button>
      </template>
    </a-modal>

    <!-- 修改密码模态框 -->
    <a-modal centered v-model:visible="updatePasswordModalVisible" title="修改密码">
      <a-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" layout="vertical">
        <a-form-item label="新的密码" name="newPassword">
          <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="resetPasswordForm">取 消</a-button>
        <a-button key="submit" type="primary" :loading="updatePwdLoading" @click="handleUpdatePassword">确 定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  message,
  Modal
} from 'ant-design-vue'
import {
  PlusOutlined,
  DownloadOutlined,
  DownOutlined,
  DeleteOutlined,
  UnlockOutlined,
  LockOutlined
} from '@ant-design/icons-vue'
import moment from 'moment'
import { validatePhone, validatePsd, validateUsername } from '@/utils/formRules'
import md5 from 'md5-node'
import { addUser, delUser, getAllUser, updateInfo, updatePsd } from '@/apis/admin/user'

export default {
  components: {
    PlusOutlined,
    DownloadOutlined,
    DownOutlined,
    DeleteOutlined,
    UnlockOutlined,
    LockOutlined
  },
  setup() {
    // 数据状态
    const userList = ref([])
    const loading = ref(false)
    const selectedRowKeys = ref([])
    const addModalVisible = ref(false)
    const updatePasswordModalVisible = ref(false)
    const currentEditUser = ref(null);
    const addFormRef = ref(null);
    const passwordFormRef = ref(null);
    const updatePwdLoading = ref(false);
    const addFormLoading = ref(false);

    const tableContainerRef = ref();
    const tableHeight = ref(600);
    onMounted(() => {
      tableHeight.value = tableContainerRef.value.clientHeight - 88;
    })



    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: false,
      showTotal: total => `总共 ${total} 条`
    })

    // 搜索表单
    const searchForm = reactive({
      username: '',
      nickname: '',
      phone: '',
      isBan: undefined,
      create_time: []
    })

    // 添加用户表单
    const addForm = reactive({
      username: '',
      password: '',
      nickname: '',
      phone: '',
      sex: undefined,
      isBan: undefined
    })

    // 修改密码表单
    const passwordForm = reactive({
      newPassword: '',
      confirmPassword: ''
    })

    // 表单验证规则
    const addFormRules = reactive({
      username: [
        { required: true, message: '请输入用户名' },
        { validator: validateUsername, message: '用户名8-12位由数字和字母组成' }
      ],
      password: [
        { required: true, message: '请输入密码' },
        { validator: validatePsd, message: '密码6-12位由数字或字母组成' }
      ],
      phone: [
        { required: true, message: '请输入电话号码' },
        { validator: validatePhone, message: '请输入合法电话号码' }
      ],
      isBan: [
        { required: true, message: '请选择状态' }
      ]
    })

    const passwordRules = reactive({
      newPassword: [
        { required: true, message: '请输入新密码' },
        {
          validator: (_, value) => {
            if (!validatePsd(value)) {
              return Promise.reject('密码6-12位由数字和字母组成')
            }
            return Promise.resolve()
          }
        }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码' },
        {
          validator: (_, value) => {
            console.log(_, value);

            if (value !== passwordForm.newPassword) {
              return Promise.reject('两次输入的密码不一致')
            }
            return Promise.resolve()
          }
        }
      ]
    })

    // 表格列配置
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username'
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        key: 'nickname'
      },
      {
        title: '头像',
        key: 'avatar',
        dataIndex: 'avatar'
      },
      {
        title: '电话号码',
        dataIndex: 'phone',
        key: 'phone'
      },
      {
        title: '是否禁用',
        key: 'isBan',
        dataIndex: 'isBan'
      },
      {
        title: '是否管理员',
        key: 'isAdmin',
        dataIndex: 'isAdmin'
      },
      {
        title: '创建时间',
        key: 'create_time',
        dataIndex: 'create_time'
      },
      {
        title: '修改时间',
        key: 'update_time',
        dataIndex: 'update_time'
      },
      {
        title: '操作',
        key: 'action'
      }
    ]

    // 生命周期钩子
    onMounted(() => {
      fetchUserList()
    })

    // 方法
    const fetchUserList = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.current,
          limit: pagination.pageSize,
          ...searchForm,
        }
        if (!params.create_time || !params.create_time.length) delete params.create_time;


        const res = await getAllUser(params)
        if (res.code === 0) {
          userList.value = res.data.list
          pagination.total = res.data.total
        } else {
          message.error(res.message)
        }
      } catch (error) {
        message.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      fetchUserList()
    }

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        if (Array.isArray(searchForm[key])) {
          searchForm[key] = []
        } else {
          searchForm[key] = undefined
        }
      })
      handleSearch()
    }

    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current
      pagination.pageSize = pag.pageSize
      fetchUserList()
    }

    const onSelectChange = selectedKeys => {
      selectedRowKeys.value = selectedKeys
    }

    const handleBatchAction = ({ key }) => {
      if (selectedRowKeys.value.length === 0) {
        message.warning('请至少选择一条记录')
        return
      }

      switch (key) {
        case 'delete':
          Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedRowKeys.value.length} 条记录吗？`,
            onOk: batchDelete
          })
          break
        case 'ice':
          batchUpdateStatus(1)
          break
        case 'un-ice':
          batchUpdateStatus(0)
          break
      }
    }

    const batchDelete = async () => {
      try {
        const res = await delUser({ user_id: selectedRowKeys.value })
        if (res.code === 0) {
          message.success('删除成功')
          selectedRowKeys.value = []
          fetchUserList()
        } else {
          message.error(res.message)
        }
      } catch (error) {
        message.error('删除失败')
      }
    }

    const batchUpdateStatus = async status => {
      try {
        // 这里需要根据实际API调整
        const promises = selectedRowKeys.value.map(id =>
          updateInfo({ user_id: id, isBan: status })
        )

        await Promise.all(promises)
        message.success('操作成功')
        selectedRowKeys.value = []
        fetchUserList()
      } catch (error) {
        message.error('操作失败')
      }
    }

    const showAddModal = () => {
      addModalVisible.value = true
    }

    const handleAddUser = async () => {
      try {
        addFormLoading.value = true
        await addFormRef.value.validate((valid) => {
          console.log(valid);
        })
        const res = await addUser({
          ...addForm,
          password: md5(addForm.password)
        })

        if (res.code === 0) {
          message.success('添加成功')
          addModalVisible.value = false
          resetAddForm()
          fetchUserList()
        } else {
          message.error(res.message)
        }
      } catch (error) {
        console.log('验证失败:', error)
      } finally{
        addFormLoading.value = false
      }
    }

    const resetAddForm = () => {
      addFormRef.value?.resetFields()
    }

    const showUpdatePasswordModal = record => {
      currentEditUser.value = record
      updatePasswordModalVisible.value = true
    }

    const handleUpdatePassword = async () => {
      try {
        updatePwdLoading.value = true;

        await passwordFormRef.value.validate();

        const res = await updatePsd({
          user_id: currentEditUser.value.user_id,
          password: md5(passwordForm.newPassword),
          confirmPsd: md5(passwordForm.newPassword)
        })

        if (res.code === 0) {
          message.success('密码修改成功')
          resetPasswordForm()
        } else {
          message.error(res.message)
        }
        updatePwdLoading.value = false;
      } catch (error) {
        console.log('验证失败:', error)
      } finally {
        updatePwdLoading.value = false;
      }
    }

    const resetPasswordForm = () => {
      passwordFormRef.value?.resetFields()
      currentEditUser.value = null
      updatePasswordModalVisible.value = false
    }

    const handleSwitchChange = async (checked, record) => {
      try {
        const res = await updateInfo({
          user_id: record.user_id,
          isBan: checked
        })

        if (res.code === 0) {
          message.success('状态更新成功')
          fetchUserList()
        } else {
          message.error(res.message)
        }
      } catch (error) {
        message.error('状态更新失败')
      }
    }

    const confirmDelete = async record => {
      try {
        const res = await delUser({ user_id: [record.user_id] })
        if (res.code === 0) {
          message.success('删除成功')
          fetchUserList()
        } else {
          message.error(res.message)
        }
      } catch (error) {
        message.error('删除失败')
      }
    }


    const formatTime = timestamp => {
      return moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
    }

    return {
      // 状态
      userList,
      loading,
      selectedRowKeys,
      addModalVisible,
      updatePasswordModalVisible,
      pagination,

      tableContainerRef,
      tableHeight,

      // 表单数据
      searchForm,
      addForm,
      passwordForm,
      updatePwdLoading,

      // 表单引用
      addFormRef,
      passwordFormRef,

      // 配置
      columns,
      addFormRules,
      passwordRules,

      // 方法
      handleSearch,
      resetSearch,
      handleTableChange,
      onSelectChange,
      handleBatchAction,
      showAddModal,
      handleAddUser,
      resetAddForm,
      showUpdatePasswordModal,
      handleUpdatePassword,
      resetPasswordForm,
      handleSwitchChange,
      confirmDelete,
      formatTime
    }
  }
}
</script>

<style lang="less" scoped>
.user-management {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .user-form {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .form-btn {
      min-width: 140px;
    }
  }

  .table-body {
    flex: 1;

    :deep(.ant-card-body) {
      height: 100%;
      display: flex;
      flex-direction: column;

      .table-contaier {
        flex: 1;

        .ant-table {
          height: 100%;
        }
      }

    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.ant-card {
  margin-bottom: 16px;
}
</style>